package org.bigdata.framework.core.utils;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * es工具类 查询方法汇总
 * 
 * @author anhuifeng
 * 
 */
public class ElasticsearchClientUtils {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(ElasticsearchClientUtils.class);
	private static TransportClient client = TransportClientUtil
			.getTransportClient();

	/**
	 * 根据id,搜索文档
	 */
	private static void get() {
		GetResponse response = client
				.prepareGet("hymax", "hymax.qk", "59be68362c4118a95c9a9c55")
				.setOperationThreaded(false) // 默认为true,在不同的线程执行
				.get();
		System.out.println(response.getSourceAsString());

	}

	private static void search() {
//		SearchResponse response = client.prepareSearch().execute().actionGet();
		
		QueryBuilder query = QueryBuilders.matchQuery("title", "农业机械化是什么");  
        SearchResponse response = client.prepareSearch("hymax")  
                .setTypes("hymax.qk").setQuery(query).execute().actionGet(); 
        SearchHits hits = response.getHits();  
        long total = hits.getTotalHits();  
        System.out.println("total:" + total);  
        int len = hits.getHits().length;  
        System.out.println("len:" + len);  
        
//		        .setTypes("hymax_qk")
//		        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
////		        .setQuery(QueryBuilders.multiMatchQuery("科技信息", "title","keywords"))             // Query
////		        .setQuery(QueryBuilders.matchQuery("title", "机"))             // Query
//		        .setQuery(QueryBuilders.matchQuery("title", "农业机械化"))             // Query
////		        .setQuery(QueryBuilders.termQuery("status", "1"))             // Query
////		        .setPostFilter(QueryBuilders.rangeQuery("status").from(1).to(1))   // Filter
//		        .setFrom(0).setSize(60)
//		        //.setExplain(true)
////		        .addSort("create_time", SortOrder.DESC)
//		        .execute()
//		        .actionGet();
		
//		SearchHits hits = searchResponse.getHits();  
//        SearchHit[] searchHits = hits.getHits();  
//
//		List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
//		for (SearchHit hit : searchHits) {
//			results.add(hit.getSource());
//		}
//		System.out.println("result ---->>>>");
//		for (int i = 0; i < results.size(); i++) {
//			System.out.println(results.get(i)+"###");
//		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		get();
		search();
	}

}
